<?php


namespace App\Http\Response;


use App\Models\Video;
use App\Services\Uri;

class VideoResponse
{
    public static function getItemsList($items, $likeVideoIds=[], &$lastId=0, &$weight=0) :array {
        $data = [];
        foreach ($items as $item){
            $lastId = $item->id > $lastId ? $item->id : $lastId;
            $weight = $item->weight < $weight ? $item->weight : $weight;
            $video = self::toArray($item);
            // 用户已登录 更新has_like 判断是否已点赞
            self::hasLike($video, $likeVideoIds);
            $data[] = $video;
        }
        return $data;
    }

    public static function toArray(Video $item){
        $author_img = Uri::createImageUrl($item->user->image);
        $url = Uri::createVideoUrl($item['path']);
        $image = "";
        if(count($item['images'])>0){
            $image = Uri::createImageUrl($item['images'][0]['path']);
        }

        $likesNum = $item->likes_num;
        if($item->likes_num < 100){
            // 真实点赞数低于100， 在原有数值基础上，加上点赞数假数据的值。
            if($item->likes_num_fake==0){
                // 点赞数假数据为0,则在100-2000之间随机生成，并保存到数据库。
                $item->likes_num_fake = mt_rand(100,2000);
                $item->save();
            }
            $likesNum += $item->likes_num_fake;
        }

        return [
            'id' => $item->id,
            'user_id' => $item->user_id,
            'url' => $url,
            'is_recommend' => $item->is_recommend,
            'image' => $image,
            'title' => $item->title,
            'author_img' => $author_img,
            'likes_num' => $likesNum,
            'video_weight' => $item->weight,
            'review_num' => $item->review_num,
            'has_follow_author' => 0, // 是否已关注该作者
            'has_like' => 0, // 是否已点赞该视频
            'created_at' => $item->created_at,
//          'user' => $item->user
        ];
    }

    public static function hasLike(&$item, $videoIds=[]){
        if(in_array($item['id'], $videoIds)){
            $item['has_like'] = 1;
        }
    }

}
